package com.meiqiongproperty.yiguanjia.fragment.shopcart.shopcartAdapter;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.Glide;
import com.meiqiongproperty.yiguanjia.R;
import com.meiqiongproperty.yiguanjia.databinding.ShopCartItemBinding;
import com.meiqiongproperty.yiguanjia.fragment.home.adapter.OnItemClickListener;
import com.meiqiongproperty.yiguanjia.httpbean.evenBus.SelectedPrice;
import com.meiqiongproperty.yiguanjia.httpbean.evenBus.SeletedEvent;
import com.meiqiongproperty.yiguanjia.httpbean.shopcart.ShopCartListBean;
import com.meiqiongproperty.yiguanjia.utils.LogUtil;
import com.meiqiongproperty.yiguanjia.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * author: Administrator
 * date: 2017/5/20.
 * package:com.meiqiongproperty.yiguanjia.fragment.shopcart.shopcartAdapter
 */

public class ShopCartListAdapter extends RecyclerView.Adapter<ShopCartListAdapter.BindingHolder> {

    Context context;
    ShopCartItemBinding binding;
    LayoutInflater inflater;
    private OnItemClickListener mOnItemClickListener;
    List<ShopCartListBean> list_shopcart = new ArrayList<>();
    ShopCartAmountCallback mCallback;
    HashMap<Integer, Integer> shopcartAmountMap = new HashMap<Integer, Integer>();
    public HashMap<Integer, Boolean> map;
    private EventBus eventBus;
    int pos;
    double totalPrice = 0.00;
    List<Double> list_price = new ArrayList<>(list_shopcart.size());
    boolean isAllSelect=false;

    public boolean isAllSelect() {
        return isAllSelect;
    }

    public void setAllSelect(boolean allSelect) {
        isAllSelect = allSelect;
    }

    public ShopCartListAdapter(Context context, List<ShopCartListBean> list_shopcart, HashMap<Integer, Integer> shopcartAmountMap, EventBus eventBus) {
        this.context = context;
        this.list_shopcart = list_shopcart;
        this.shopcartAmountMap = shopcartAmountMap;
        map = new HashMap<>();
        this.eventBus = eventBus;
        inflater = LayoutInflater.from(context);
        init();
        initListPrice();
    }

    /**
     * 初始化list
     */
    public void initListPrice(){
        for (int i=0;i<list_shopcart.size();i++){
            list_price.add(i,0.00);
        }
    }

    public void init() {
        if (null == list_shopcart || list_shopcart.size() <= 0) {
            return;
        }
        for (int i = 0, p = list_shopcart.size(); i < p; i++) {
            map.put(i, false);
        }
    }

    public double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }

    public List<Double> getList_price() {
        return list_price;
    }

    public void setList_price(List<Double> list_price) {
        this.list_price = list_price;
    }

    @Override
    public ShopCartListAdapter.BindingHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        binding = DataBindingUtil.inflate(inflater, R.layout.shop_cart_item, parent, false);
        ShopCartListAdapter.BindingHolder holder = new ShopCartListAdapter.BindingHolder(binding.getRoot());
        holder.setBinding(binding);
        return holder;
    }

    @Override
    public void onBindViewHolder(final ShopCartListAdapter.BindingHolder holder, final int position) {
        pos = position;
        final ShopCartListBean bean = list_shopcart.get(position);
        Glide.with(context).load(bean.getShopCartImgUrl()
                .toString()).into( holder.binding.shopCartItemImage);
        if (mOnItemClickListener != null) {
            /**
             * 这里加了判断，itemViewHolder.itemView.hasOnClickListeners()
             * 目的是减少对象的创建，如果已经为view设置了click监听事件,就不用重复设置了
             * 不然每次调用onBindViewHolder方法，都会创建一个监听事件对象，增加了内存的开销
             */
            if (!holder.itemView.hasOnClickListeners()) {
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position = holder.getPosition();
                        mOnItemClickListener.onItemClick(v, position);
                    }
                });
            }
        }
        if (map != null) {
            holder.binding.shopCartItemCheckbox.setChecked((map.get(position)));
        } else {
            holder.binding.shopCartItemCheckbox.setChecked(false);
        }

        holder.binding.shopCartItemCheckbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LogUtil.d("xxx"+selected(map));
//                holder.binding.shopCartItemCheckbox.setChecked((map.get(position)));
                if (map != null) {
                   if (selected(map)==0){

                   }

                    if (map.get(position)) {
                        map.put(position, false);
                        list_price.set(position,0.00);
//                        setList_price(list_price);
                        eventBus.post(new SeletedEvent(selected(map)));
                    } else {
                        map.put(position, Boolean.TRUE);
                        double price=calculateItemPrice(position,Utils.toDouble(bean.getShopCartPrice()));
                        list_price.set(position,price);
//                        setList_price(list_price);
                        eventBus.post(new SeletedEvent(selected(map)));
                    }

                }
            }
        });

        holder.binding.shopCartListTitle.setText(bean.getShopCartTitle());
        holder.binding.shopCartItemPrice.setText("￥" + bean.getShopCartPrice());
        holder.binding.etShopCartItemAmount.setText(shopcartAmountMap.get(position) + "");

        holder.binding.shopCartItemDecrease.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtil.d("isAllSelect==========>"+isAllSelect);
                if (shopcartAmountMap.get(position) > 1) {
                    mCallback.refreshAmount(position, false);
                }
                if (map.get(position)){
                    double price=calculateItemPrice(position,Utils.toDouble(bean.getShopCartPrice()));
                    list_price.set(position,price);
                    eventBus.post(new SelectedPrice(price));
                }else{
                    list_price.set(position,0.00);
                }
            }
        });

        holder.binding.shopCartItemIncrease.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCallback.refreshAmount(position, true);
                if (map.get(position)){
                    double price=calculateItemPrice(position,Utils.toDouble(bean.getShopCartPrice()));
                    list_price.set(position,price);
                    eventBus.post(new SelectedPrice(price));
                }else{
                    list_price.set(position,0.00);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return list_shopcart.size();
    }

    public class BindingHolder extends RecyclerView.ViewHolder {
        ShopCartItemBinding binding;

        public ShopCartItemBinding getBinding() {
            return binding;
        }

        public void setBinding(ShopCartItemBinding binding) {
            this.binding = binding;
        }

        public BindingHolder(View itemView) {
            super(itemView);
        }
    }

    public void setOnItemClickListener(OnItemClickListener mOnItemClickListener) {
        this.mOnItemClickListener = mOnItemClickListener;
    }

    public List<ShopCartListBean> getList_shopcart() {
        return list_shopcart;
    }

    public void setList_shopcart(List<ShopCartListBean> list_shopcart) {
        this.list_shopcart = list_shopcart;
        notifyDataSetChanged();
    }

    public void setShopCartAmount(int position, boolean isAdd) {
        int amount = shopcartAmountMap.get(position);
        if (amount == 0 && !isAdd)
            return;
        shopcartAmountMap.put(position, isAdd ? (amount + 1) : (amount - 1));
        notifyItemChanged(position);
    }

    public interface ShopCartAmountCallback {
        // 处理美食份数选择事件
        void refreshAmount(int pos, boolean isAdd);
    }

    public void setCallback(ShopCartAmountCallback callback) {
        this.mCallback = callback;
    }

    public HashMap<Integer, Boolean> getMap() {
        return map;
    }

    public void setMap(HashMap<Integer, Boolean> map) {
        this.map = map;
        notifyDataSetChanged();
    }


    /**
     * 计算每个item的价格总数
     */
    public double calculateItemPrice(int position, double price) {
        totalPrice = shopcartAmountMap.get(position) * price;
        setTotalPrice(totalPrice);
        return totalPrice;
    }

    /**
     * 选中的条目数量
     *
     * @param map
     * @return
     */
    private int selected(HashMap<Integer, Boolean> map) {
        int size = 0;
        for (Integer key : map.keySet()) {
            if (map.get(key)) {
                size++;
            }
        }
        return size;
    }

    public HashMap<Integer, Integer> getShopcartAmountMap() {
        return shopcartAmountMap;
    }
}
